package com.sw.haruka.ui.widget;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.Display;
import android.view.View;

import androidx.annotation.Nullable;

import com.sw.haruka.App;

import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * Created by shqyang on 06/06/2021
 */
public class ProgressView extends View {

    private Paint paint;

    private int percentOld;
    private float percentNow;
    private float hz = 60f;
    private ScheduledExecutorService drawService;
    private Future progressingThread;


    public ProgressView(Context context) {
        super(context);
    }

    public ProgressView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        paint = new Paint();
        paint.setColor(Color.BLUE);
        drawService = new ScheduledThreadPoolExecutor(1);
        hz = App.Companion.getHz();
    }

    private float getHz() {
        return getDisplay().getRefreshRate();
    }

    public ProgressView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @SuppressLint("DrawAllocation")
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        float r = getWidth() * percentNow / 100;
        RectF progressBlock = new RectF(0, 0, r, getHeight());
        canvas.drawRect(progressBlock, paint);
    }

    public void setPercentNow(float percentNow) {
        cancelProgressing();
        progressing(percentNow);
    }

    private void progressing(float pn) {
        if (pn <= percentNow) {
            return;
        }
        float chip = (pn - percentNow) / hz;
        Runnable runnable = () -> {
            percentNow += chip;
            invalidate();
            if (percentNow >= pn) {
                cancelProgressing();
            }
        };
        progressingThread = drawService.scheduleAtFixedRate(runnable, 0, 1000/60, TimeUnit.MILLISECONDS);
    }

    private void cancelProgressing() {
        if (progressingThread != null) {
            progressingThread.cancel(false);
            progressingThread = null;
        }
    }

    public void setProgressColor(int color) {
        paint.setColor(color);
    }
}
